package concurrentV;

public class ThreeThreadPrint123 {
    private static final Object lock = new Object(); // 共享锁
    private static int count = 1; // 当前要打印的数字 1,2,3
    private final int rank; // 每个线程的固定序号 (0, 1, 2)

    public ThreeThreadPrint123(int rank) {
        this.rank = rank;
    }

    public void print123() {
        for (int i = 0; i < 10; i++) { // 每个线程重复打印 10 次
            synchronized (lock) {
                // 检查是否轮到当前线程打印
                while ((count - 1) % 3 != rank) {
                    try {
                        lock.wait(); // 当前线程等待
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt(); // 恢复中断状态
                        return;
                    }
                }

                // 打印数字
                System.out.println(Thread.currentThread().getName() + " -> " + count);

                // 更新 `count`，并通知其他线程
                count = count % 3 + 1;// 注意是% 3 +1 而不是+1 % 3
                lock.notifyAll();
            }
        }
    }

    public static void main(String[] args) {
        // 创建三个线程，每个线程打印特定序号的数字
        new Thread(() -> new ThreeThreadPrint123(0).print123(), "Thread-1").start();
        new Thread(() -> new ThreeThreadPrint123(1).print123(), "Thread-2").start();
        new Thread(() -> new ThreeThreadPrint123(2).print123(), "Thread-3").start();
    }
}
